package we3d.renderer.cc 
{
	import we3d.View3d;
	import we3d.core.Camera3d;
	import we3d.scene.SceneObject;
	import we3d.mesh.Face;
	import we3d.mesh.Vertex;
	import we3d.math.Matrix3d;
	import we3d.renderer.IObjectRenderer;
	
	public class CCDefault implements IObjectRenderer
	{
		public function CCDefault () {}
		
		public function render (view:View3d, o:SceneObject, cgv:Matrix3d) :void {
			
			var j:int = 0;
			var r:Array = o.polygons;
			var L:int = r.length;
			
			var ofc:int = o.frameCounter;
			var gv:Matrix3d = o.transform.gv;
			
			var v:Camera3d = view.scene.cam;
			var camx:Number = v.transform.gv.m;
			var camy:Number = v.transform.gv.n;
			var camz:Number = v.transform.gv.o;
			
			var k:int;
			var pL:int;
			var p:Face;
			var vtxs:Array;
			var vtxa:Vertex;
			var vtxb:Vertex;
			var x:Number;
			var y:Number;
			var z:Number;
			
			for(j=0; j<L; j++) 
			{
				p = r[j];
				
				pL = p.vLen;
				if(pL < 2) continue;
				
				vtxb = p.normal;
				vtxb.wz = gv.c * vtxb.x + gv.g * vtxb.y + gv.k * vtxb.z;
				vtxb.wy = gv.b * vtxb.x + gv.f * vtxb.y + gv.j * vtxb.z;
				vtxb.wx = gv.a * vtxb.x + gv.e * vtxb.y + gv.i * vtxb.z;
				
				if(pL > 2 && p.surface.hideBackfaces) {
					vtxa = p.a;
					z = gv.c * vtxa.x + gv.g * vtxa.y + gv.k * vtxa.z + gv.o - camz;
					y = gv.b * vtxa.x + gv.f * vtxa.y + gv.j * vtxa.z + gv.n - camy;
					x = gv.a * vtxa.x + gv.e * vtxa.y + gv.i * vtxa.z + gv.m - camx;
				
					if(x*vtxb.wx + y*vtxb.wy + z*vtxb.wz < 0) continue;
				}
				
				vtxs = p.vtxs;
				
				for(k=0; k<pL; k++) {
					vtxb = vtxs[k];
					if(vtxb.frameCounter1 != ofc) {
						vtxb.wz = cgv.c * vtxb.x + cgv.g * vtxb.y + cgv.k * vtxb.z + cgv.o;
						vtxb.wy = cgv.b * vtxb.x + cgv.f * vtxb.y + cgv.j * vtxb.z + cgv.n;
						vtxb.wx = cgv.a * vtxb.x + cgv.e * vtxb.y + cgv.i * vtxb.z + cgv.m + v._nearClipping;
						if(vtxb.wz > 0) {
							vtxb.sx = v.t + vtxb.wx/vtxb.wz * v.t;
							vtxb.sy = v.s - vtxb.wy/vtxb.wz * v.s;
						}else{
							vtxb.sx = v.t + vtxb.wx* v.t;
							vtxb.sy = v.s - vtxb.wy * v.s;
						}
						vtxb.frameCounter1 = ofc;
					}
				}
					
				o.polyRenderer.drawPoly(view, p);
			}
			
		}
	}
	
}